<template>
  <t-dialog v-model:visible="model" :header="dialogTitle" :confirm-loading="confirmPending" confirm-btn="确定" destroy-on-close @close="handleClose" @confirm="handleConfirm">
    <t-form ref="dialogForm" :data="formData" :rules="formRules">
      <t-form-item label="内容名称" name="contentId">
        <t-select v-model="formData.contentId" placeholder="请输入内容名称" filterable :options="contentOptions" :loading="contentSearchPending" @search="handkeContentSearch" />
      </t-form-item>
      <t-form-item label="票名称" name="ticketName">
        <t-input v-model="formData.ticketName" placeholder="请输入票名称" />
      </t-form-item>
      <t-form-item label="票价" name="ticketPrice">
        <t-input-number v-model="formData.ticketPrice" placeholder="请输入票价" />
      </t-form-item>
      <t-form-item label="启用" name="enabled">
        <t-switch v-model="formData.enabled" :custom-value="[EnabledStatus.ENABLED, EnabledStatus.DISABLED]" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import type { FormInstanceFunctions, FormRules } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { computed, reactive, ref, useTemplateRef, watchEffect } from 'vue'

import { EnabledStatus } from '@/api/model/common'
import type { TicketReqData } from '@/api/model/ticket'
import { createTicket, getTicketContentDetail, getTicketContentPageList, updateTicket } from '@/api/ticket'
import useSearchSelect from '@/hooks/selectSearch'

export type TicketFormDialogData = TicketReqData
interface Prop {
  id?: string
  data?: TicketFormDialogData
}
const props = defineProps<Prop>()
const emits = defineEmits<{
  (e: 'success'): void
}>()

const model = defineModel<boolean, 'visible'>('visible')

const isEditModel = computed(() => !!props.id)
const dialogTitle = computed(() => (isEditModel.value ? '编辑票' : '添加票'))
const DEFAULT_DATA: TicketFormDialogData = {
  contentId: '',
  ticketName: '',
  ticketPrice: 0,
  enabled: EnabledStatus.ENABLED,
}
const formData = reactive<TicketReqData>(props.data ?? { ...DEFAULT_DATA })
watchEffect(() => {
  Object.assign(formData, props.data ?? DEFAULT_DATA)
})
const formRules: FormRules<TicketReqData> = {
  contentId: [{ required: true, message: '请输入内容名称', type: 'error' }],
  ticketName: [{ required: true, message: '请输入票名称', type: 'error' }],
  ticketPrice: [{ required: true, message: '请输入票价', type: 'error' }],
  enabled: [{ required: true, message: '请选择状态', type: 'error' }],
}

const { selectOptions: contentOptions, searchLoading: contentSearchPending, handleSearch: handkeContentSearch } = useSearchSelect(() => formData.contentId, async (contentId) => {
  const res = await getTicketContentDetail(contentId)
  return ({ label: res.contentName, value: res.id })
}, async (_query) => {
  const res = await getTicketContentPageList({ page: 1, size: 10, contentName: _query, enabled: EnabledStatus.ENABLED })
  return res.data.map(item => ({ label: item.contentName, value: item.id }))
})

const dialogForm = useTemplateRef<FormInstanceFunctions<typeof formData>>('dialogForm')
const confirmPending = ref(false)
const handleConfirm = () => {
  dialogForm.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      confirmPending.value = true
      if (isEditModel.value) {
        updateTicket({ id: props.id!, ...formData }).then(() => {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('更新成功')
          emits('success')
        })
      }
      else {
        createTicket(formData).then(() => {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('创建成功')
          emits('success')
        })
      }
    }
  })
}
function handleClose() {
  Object.assign(formData, DEFAULT_DATA)
}
</script>
<style scoped>

</style>
